package com.ning.city.exception;

import com.ning.city.vo.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Ning 242741154@qq.com
 * @date 2021/1/7 16:16
 */
@Slf4j
@ResponseBody
@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(value = Exception.class)
    public CommonResult<?> handle(Exception e) {
        CommonResult<?> result = new CommonResult<>();
        List<String> list = new ArrayList<>();
        if (e instanceof BindException) {
            result.setCode(430);
            List<ObjectError> errors = ((BindException) e).getAllErrors();
            for (ObjectError error : errors) {
                list.add(error.getDefaultMessage());
            }
        } else {
            result.setCode(400);
            list.add("请求发生错误");
            log.error(e.getMessage());
            e.printStackTrace();
        }
        result.setErrors(list);
        return result;
    }
}
